//
//  BooksTableViewController.swift
//  ReadingNow
//
//  Created by iOS Developer on 2017/6/19.
//  Copyright © 2017年 lig. All rights reserved.
//

import UIKit
import Alamofire
import Kanna
import Kingfisher

class BooksTableViewController: UITableViewController, UISearchBarDelegate {
    var bookURLs = [String]()
    var BookCellContentCache = [Int:BookCellContent]()
    @IBOutlet weak var searchBar: UISearchBar!
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.navigationBar.barStyle = .blackTranslucent
        navigationController?.navigationBar.barTintColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)
        navigationController?.navigationBar.tintColor = .white
        
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            self.BookCellContentCache.removeAll()
            self.getMyBookList()
        })
        tableView.mj_header.beginRefreshing()
        searchBar.setValue("取消", forKey: "_cancelButtonText")
        searchBar.delegate = self
    }
    // MARK: - Search Bar delegate
    
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searchBar.showsCancelButton = false
        searchBar.resignFirstResponder()
        searchBar.text = ""
    }
    func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
        searchBar.showsCancelButton = true
        return true
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        let search = searchBar.text ?? ""
        searchBar.showsCancelButton = false
        searchBar.resignFirstResponder()
        searchBar.text = ""
        if !search.isEmpty {
            performSegue(withIdentifier: "show search view", sender: search)
        }
    }
    @IBAction func getDefaultBooks(_ sender: Any) {
        tableView.mj_header.beginRefreshing()
        Alamofire.request("https://git.oschina.net/li93gang/ReadingCurrent/raw/master/qu.json")
            .responseJSON(queue: DispatchQueue.main, options: .allowFragments) {[weak weakSelf = self] resp in
                if resp.result.isSuccess {
                    if let books = resp.result.value as? [Any] {
                        let URLs: [String] = books.map{($0 as! Dictionary)["url"]!}
                        
                        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
                        let documentDirectory = paths[0] as! String
                        let path = documentDirectory.appending("/urls.plist")
                        (URLs as NSArray).write(toFile: path, atomically: false)
                        weakSelf?.getMyBookList()
                    }
                }else {
                    let alert = UIAlertController(title: "提示", message: resp.result.error?.localizedDescription, preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "确定", style: .default))
                    weakSelf?.present(alert, animated: true)
                }
        }
        
    }
    
    func getMyBookList(){
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
        let documentDirectory = paths[0] as! String
        let path = documentDirectory.appending("/urls.plist")
        let fileManager = FileManager.default
        if(!fileManager.fileExists(atPath: path)){
            let bundlePath = Bundle.main.path(forResource: "urls", ofType: "plist")!
            do{
                try fileManager.copyItem(atPath: bundlePath, toPath: path)
            }catch{
                print("copy failure.")
            }
            
        }
        
        if let array = NSArray(contentsOfFile: path) as? [String]{
            bookURLs = array
            tableView.reloadData()
        }
        tableView.mj_header.endRefreshing()
    }
    
    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        if bookURLs.count == 0 {
            tableView.separatorStyle = .none
            let bg = UILabel()
            let paraph = NSMutableParagraphStyle()
            paraph.lineSpacing = 8
            bg.attributedText = NSAttributedString(string: "好像没有想看的\n试试推荐书单", attributes: [NSDocumentTypeDocumentAttribute : NSRTFTextDocumentType,NSFontAttributeName: UIFont.boldSystemFont(ofSize: 18),NSParagraphStyleAttributeName:paraph,NSForegroundColorAttributeName: #colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1)])
            bg.numberOfLines = 2
            bg.textAlignment = .center
            tableView.backgroundView = bg
        }else {
            tableView.separatorStyle = .singleLine
            tableView.backgroundView = nil
        }
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return bookURLs.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "book cell", for: indexPath) as! BookTableViewCell
        cell.nameAuther.text = "";cell.lastUpdateTime.text = "";
        cell.lastChapter.setTitle("", for: .normal)
        cell.lastChapter.isUserInteractionEnabled = false
        cell.isUserInteractionEnabled = false
        //chech weather has local cache
        if let cellCache = BookCellContentCache[indexPath.row] {
            cell.nameAuther.text = cellCache.name + "\t" + cellCache.author
            cell.lastUpdateTime.text = cellCache.time
            cell.lastChapter.setTitle( cellCache.chapter, for: .normal)
            cell.lastChapter.latestedPath = cellCache.url
            cell.bookHeader.kf.setImage(with: URL(string: cellCache.img))
            cell.lastChapter.isUserInteractionEnabled = true
            cell.isUserInteractionEnabled = true
            cell.latestedTen = cellCache.latestedTen
            cell.allChapters = cellCache.all
            cell.orign.text = cellCache.host
        }else {
            //load data from net
            Alamofire.request(bookURLs[indexPath.row]).responseData(queue: DispatchQueue.main) {[weak weakSelf = self] resp in
                if let data = resp.result.value {
                    if let doc = HTML(html: data, encoding: .utf8), let dhost = resp.response?.url?.host {
                        cell.orign.text = dhost
                        if dhost == "m.qu.la" {
                            let _name = doc.xpath("//span[@class='title']").first?.text ?? ""
                            let _author = doc.xpath("//div[@class='synopsisArea_detail']/a[position()=1]/p").first?.text ?? ""
                            let _time = doc.xpath("//div[@class='synopsisArea_detail']/p[position()=3]").first?.text ?? ""
                            let _chapter = doc.xpath("//div[@class='synopsisArea_detail']/p[position()=4]/a").first?.text ?? ""
                            let _url = doc.xpath("//div[@class='synopsisArea_detail']/p[position()=4]/a").first?["href"] ?? ""
                            let _img = doc.xpath("//div[@class='synopsisArea_detail']/img").first?["src"] ?? ""
                            let _all = doc.xpath("//a[@id='AllChapterList']").first?["href"] ?? ""
                            cell.nameAuther.text = _name + "\t" + _author
                            cell.lastUpdateTime.text = _time.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
                            cell.lastChapter.setTitle( _chapter, for: .normal)
                            cell.lastChapter.latestedPath = "http://\(dhost)/" + _url
                            cell.bookHeader.kf.setImage(with: URL(string: _img))
                            cell.lastChapter.isUserInteractionEnabled = true
                            cell.isUserInteractionEnabled = true
                            cell.latestedTen.removeAll()
                            for chapter in doc.xpath("//div[@class='directoryArea']//a") {
                                cell.latestedTen.append((chapter.text!,"http://\(dhost)/" + chapter["href"]!))
                            }
                            cell.allChapters = "http://\(dhost)/" + _all
                            
                            weakSelf?.BookCellContentCache[indexPath.row] = BookCellContent(name: _name, author: _author, time: cell.lastUpdateTime.text, chapter: _chapter, url: cell.lastChapter.latestedPath, img: _img, all: cell.allChapters, latestedTen: cell.latestedTen, host: dhost)
                        }else if dhost == "m.biqudu.com" {
                            let _name = doc.xpath("//div[@class='block_txt2']/p[position()=1]").first?.text ?? ""
                            let _author = doc.xpath("//div[@class='block_txt2']/p[position()=2]").first?.text ?? ""
                            let _time = doc.xpath("//div[@class='block_txt2']/p[position()=5]").first?.text ?? ""
                            let _chapter = doc.xpath("//div[@class='block_txt2']/p[position()=6]/a").first?.text ?? ""
                            let _url = doc.xpath("//div[@class='block_txt2']/p[position()=6]/a").first?["href"] ?? ""
                            let _img = doc.xpath("//div[@class='block_img2']/img").first?["src"] ?? ""
                            let _all = doc.xpath("//div[@class='intro']/a").first?["href"] ?? ""
                            cell.nameAuther.text = _name + "\t" + _author
                            cell.lastUpdateTime.text = _time
                            cell.lastChapter.setTitle( _chapter, for: .normal)
                            cell.lastChapter.latestedPath = "http://\(dhost)/" + _url
                            cell.bookHeader.kf.setImage(with: URL(string: _img))
                            cell.lastChapter.isUserInteractionEnabled = true
                            cell.isUserInteractionEnabled = true
                            cell.latestedTen.removeAll()
                            for chapter in doc.xpath("//ul[@class='chapter']//a") {
                                cell.latestedTen.append((chapter.text!,"http://\(dhost)/" + chapter["href"]!))
                            }
                            cell.allChapters = "http://\(dhost)/" + _all
                            
                            weakSelf?.BookCellContentCache[indexPath.row] = BookCellContent(name: _name, author: _author, time: _time, chapter: _chapter, url: cell.lastChapter.latestedPath, img: _img, all: cell.allChapters, latestedTen: cell.latestedTen, host: dhost)
                        }
                    }
                }else {
                    let alert = UIAlertController(title: "提示", message: "\(indexPath.row). 内容加载失败", preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "确定", style: .default))
                    weakSelf?.present(alert, animated: true)
                }
            }
        }
        return cell
    }
    
    override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let action = UITableViewRowAction(style: .destructive, title: "移除") { (act, indexPath) in
            self.bookURLs.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)
            let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
            let documentDirectory = paths[0] as! String
            let path = documentDirectory.appending("/urls.plist")
            (self.bookURLs as NSArray).write(toFile: path, atomically: false)
        }
        return [action]
    }
    
    // MARK: - Navigation
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        //segue id 'latest ten' and 'loadContent'
        if segue.identifier == "latest ten",let cell = sender as? BookTableViewCell {
            let dest = segue.destination as! LastTenTableViewController
            dest.tenChapters = cell.latestedTen
            dest.allChapters = cell.allChapters
        }else if segue.identifier == "loadContent", let dest = segue.destination as? ContentViewController ,let btn = sender as? ChapterButton {
            dest.contentURL = btn.latestedPath
        }else if segue.identifier == "show search view", let dest = segue.destination as? SearchResultController {
            dest.searchContent = sender as! String
        }
    }
}
